package com.sky.utils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Data
@AllArgsConstructor
@Slf4j
public class OssUtil {

    private String domain;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param inputStream
     * @param objectName
     * @return
     */
    public String upload(InputStream inputStream, String objectName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String key = objectName;
        try {
            Auth auth = Auth.create(accessKeyId, accessKeySecret);
            String upToken = auth.uploadToken(bucketName);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                if(response.statusCode==200){
                    StringBuilder stringBuilder = new StringBuilder("http://");
                    stringBuilder
                            .append(domain)
                            .append("//")
                            .append(objectName);

                    log.info("文件上传到:{}", stringBuilder.toString());
                    return stringBuilder.toString();
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
                log.error(r.toString());
                try {
                    log.error(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return null;
    }
}
